﻿using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Wicresoft.UnifyShow.Business;
using Wicresoft.UnifyShow2.Portal.Models;
using Wicresoft.UnifyShow2.Portal.Service;

namespace Wicresoft.UnifyShow2.Portal.Controllers
{
    [Authorize]
    public class OpsReportController : BaseController
    {
        //
        // GET: /AdminDocument/

        private IUser_X user;
        private ICommonResource resource;
        private ISiteBranch siteBranch;

        protected override void Dispose(bool disposing)
        {
            ((IDisposable)user).Dispose();
            ((IDisposable)resource).Dispose();
            ((IDisposable)siteBranch).Dispose();
        }

        public OpsReportController() { }

        [InjectionConstructor]
        public OpsReportController(IUser_X user, ICommonResource resource, ISiteBranch siteBranch)
        {
            this.user = user;
            this.resource = resource;
            this.siteBranch = siteBranch;
        }

        [Authorize]
        public ActionResult Admin()
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            if (!IsConfigAdmin) return new HttpStatusCodeResult(403);
            ViewBag.Info = false;

            //根据当前用户所在公司名称返回SiteBranchModel
            List<US_SiteAccessModel> listUS = new List<US_SiteAccessModel>();
            List<SiteBranchModel> listSites = new List<SiteBranchModel>();
            OpsAddModel opsAdd = new OpsAddModel();

            if (USER_X.Company == "福建省烟草专卖局")
            {
                listSites = siteBranch.GetSiteALLBranch();
            }
            else
            {
                listSites.Add(siteBranch.GetSiteBranchByName(USER_X.Company));
            }
            foreach (var item in listSites)
            {
                if (!string.IsNullOrEmpty(item.Alias))
                {
                    US_SiteAccessModel usmodel = new US_SiteAccessModel();
                    usmodel.ID = item.ID;
                    usmodel.Alias = item.Alias;
                    usmodel.IsAccess = false;
                    listUS.Add(usmodel);
                }
            }
            opsAdd.US_SiteAccessList = listUS;
            return View(opsAdd);

        }

        [HttpPost]
        public ActionResult Admin(OpsAddModel model)
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var CurrentUser = user.GetUser_XByName(User.Identity.Name);
            if (CurrentUser == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = CurrentUser.Department;
            ViewBag.UserCompany = CurrentUser.Company;

            if (!IsConfigAdmin) return new HttpStatusCodeResult(403);
            ViewBag.Info = false;

            var today = DateTime.Today.ToString("yyyyMMdd");
            var guid = Guid.NewGuid().ToString();
            string filePath = Server.MapPath(Path.Combine(ConfigurationManager.AppSettings["CommonResourcePath"], today, guid));
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }

            foreach (string myfile in Request.Files)
            {
                if (!DocumentService.HasFile(Request.Files[myfile])) continue;
                string fileName = Path.GetFileName(Request.Files[myfile].FileName);
                string fullFilePath = Path.Combine(filePath, fileName);
                string _siteid = null;
                foreach (var item in model.US_SiteAccessList)
                {
                    if (item.IsAccess == true)
                    {
                        _siteid = _siteid + ";" + item.ID;
                    }

                }

                CommonResourceModel ops = new CommonResourceModel()
                {
                    DName = model.DName,
                    FileName = fileName,
                    SiteID = _siteid,
                    Type = "1",//运维报告
                    Keywords = model.Keywords,
                    Submitter = CurrentUser.Name,
                    CreateTime = DateTime.Now,
                    Url = Path.Combine(ConfigurationManager.AppSettings["CommonResourcePath"], today, guid, fileName).Replace('\\', '/')
                };

                try
                {
                    Request.Files[myfile].SaveAs(Path.Combine(filePath, fileName));
                    var ret = resource.Add(ops);
                    ViewBag.Info = true;
                }
                catch (Exception ex)
                {
                    throw new Exception("操作失败，请重新上传.");
                }

            }
            return View(model);
        }


        [HttpPost]
        public JsonResult OpsList(int page, int rows, string sort, string order)
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            List<SiteBranchModel> listSites = new List<SiteBranchModel>();
            listSites.Add(siteBranch.GetSiteBranchByName(USER_X.Company));
            string siteid = null;
            foreach (var item in listSites)
            {
                siteid = Convert.ToString(item.ID);
            }
            decimal totalCount = 0;
            if (string.IsNullOrEmpty(sort)) { sort = "ID"; }
            if (string.IsNullOrEmpty(order)) { order = "Descending"; }
            var list = resource.GetAllOpsDocuments(siteid, out totalCount, page, rows, sort, order);
            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetURL(string id)
        {
            var model = new CommonResourceModel();
            string url = string.Empty;
            if (!string.IsNullOrEmpty(id))
            {
                int myid = Convert.ToInt32(id);
                model = resource.GetByID(myid);
                url = model.Url;
            }
            return Json(Server.UrlEncode(url), JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult PostSearchResource(string param, string startTime, string endTime, int page, int rows, string sort, string order)
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            List<SiteBranchModel> listSites = new List<SiteBranchModel>();
            listSites.Add(siteBranch.GetSiteBranchByName(USER_X.Company));
            DateTime sTime, eTime;

            if (string.IsNullOrEmpty(startTime))
                sTime = Convert.ToDateTime("2009/12/31");
            else
                sTime = Convert.ToDateTime(startTime);
            if (string.IsNullOrEmpty(endTime))
                eTime = Convert.ToDateTime("2050/12/31");
            else
                eTime = Convert.ToDateTime(startTime);



            string siteid = null;
            foreach (var item in listSites)
            {
                siteid = Convert.ToString(item.ID);
            }
            decimal totalCount = 0;
            List<CommonResourceModel> list = new List<CommonResourceModel>();
            if (string.IsNullOrEmpty(sort)) { sort = "ID"; }
            if (string.IsNullOrEmpty(order)) { order = "Ascending"; }
            if (string.IsNullOrEmpty(param))
                list = resource.GetAllOpsDocuments(siteid, out totalCount, page, rows, sort, order);
            else
                list = resource.GetOpsByKeywords(out totalCount, param, page, rows, sort, order);

            return Json(new { rows = list, total = totalCount }, JsonRequestBehavior.AllowGet);
        }


        public ActionResult Search()
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            if (!IsConfigAdmin)
                ViewBag.IsConfigAdmin = false;

            return View();
        }

        public ActionResult DownLoad(int id)
        {
            byte[] files;
            string type, filename;
            DocumentHelper.GetFile(id, out files, out type, out filename);
            return File(files, type, filename);
        }

        public ActionResult ListAdmin()
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            if (!IsConfigAdmin) return new HttpStatusCodeResult(403);

            return PartialView();
        }

        public ActionResult List()
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            List<SiteBranchModel> listSites = new List<SiteBranchModel>();
            listSites.Add(siteBranch.GetSiteBranchByName(USER_X.Company));
            string siteid = null;
            foreach (var item in listSites)
            {
                siteid = Convert.ToString(item.ID);
            }

            var model = resource.GetAllOpsInfo(siteid).OrderByDescending(o => o.CreateTime).Take(5).ToList();
            //var model = DocumentHelper.GetList().OrderByDescending(o => o.CreateTime).Take(5).ToList();
            return PartialView(model);
        }

        [HttpPost]
        public JsonResult FileDelete(int ID)
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var CurrentUser = user.GetUser_XByName(User.Identity.Name);
            if (CurrentUser == null)
                throw new Exception("USER_X is null.");

            var file = resource.GetByID(ID);

            if (file != null)
            {
                if (file.Submitter == CurrentUser.Name)
                {
                    //本地删除
                    string filePath = Server.MapPath(ConfigurationManager.AppSettings["CommonResourcePath"]);
                    string fullFilePath = Path.Combine(filePath, file.FileName);
                    if (System.IO.File.Exists(fullFilePath))
                    {
                        System.IO.File.Delete(fullFilePath);
                    }
                    //数据库删除
                    var result = resource.Delete(ID) ? "OK" : "Error";
                    return Json(result, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json("Warning", JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                return Json("Error", JsonRequestBehavior.AllowGet);
            }

        }

    }
}
